<?php
declare (strict_types=1);

namespace app\listener;

use app\common\model\Consulting;
use app\common\model\ConsultingMessage;
use app\common\service\GatewayClientServer;
use app\index\service\MessageSendService;

class ConsultingLawyerJoined
{

    /**
     * 律师加入聊天 事件监听处理
     *
     * @return mixed
     */
    public function handle(Consulting $consulting)
    {

        $lawyerId = $consulting->lawyerId;

        if (!is_id($lawyerId)) {
            return;
        }

        // 咨询分配律师后

        // 发律师名片消息
        $content = [
            'id' => $lawyerId
        ];
        $this->getMessageSendService()->sendSystemMessage($consulting, 0, ConsultingMessage::LAWYER, $content);

        // 匹配律师后，如果该咨询已提问，那么发消息说律师正在分析案情
        if($consulting->isAsked == 1){
            $content = [
                'text' => '我已收到您的信息，正在为您分析案情，请耐心等待'
            ];
            $this->getMessageSendService()->sendMemberMessage($consulting, 1, $lawyerId, ConsultingMessage::TEXT, $content);
        }

        // 给 律师 发 默认系统消息
        $content = [
            'icon' => ['url' => image_url('/storage/static/images/icon/icon_msg.png')],
            'templates' => [['type' => 'text', 'red' => '102', 'text' => '您的信息已被加密，请放心输入',]],
        ];
        $this->getMessageSendService()->sendSystemMessage($consulting, $lawyerId, ConsultingMessage::SYSTEM, $content);

        // 律师加入后，给律师推送咨询列表更新消息
        $data = [
            'action' => CHAT_LIST,
            'data' => []
        ];
        $this->getGatewayClientServer()->sendToUid($lawyerId, json_encode($data));

        // 律师加入后，更新工作台
        $data = [
            'action' => WORKBENCH_UPDATE,
            'data' => [],
        ];
        $this->getGatewayClientServer()->sendToUid($lawyerId, json_encode($data));

        // 律师加入后，更新红点
        $data = [
            'action' => REDDOT,
            'data' => [],
        ];
        $this->getGatewayClientServer()->sendToUid($lawyerId, json_encode($data));

    }

    private function getMessageSendService(): MessageSendService
    {
        return app(MessageSendService::class);
    }

    private function getGatewayClientServer(): GatewayClientServer
    {
        return app(GatewayClientServer::class);
    }
}
